/*
 * Copyright (c) 2011 Nathan Byrd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.stackconfig.web.gwt.client.widgets;

import com.allen_sauer.gwt.dnd.client.PickupDragController;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Panel to contain stack components.  Used to make clones of widgets when dragging
 * See: http://allen-sauer.com/com.allen_sauer.gwt.dnd.demo.DragDropDemo/DragDropDemo.html#PaletteExample
 */
public class ComponentPanel extends VerticalPanel {
    private final PickupDragController dragController;

    /**
     * Create a new ComponentPanel
     *
     * @param dragController controller used in dragging widgets
     */
    public ComponentPanel(PickupDragController dragController) {
        this.dragController = dragController;
        setSpacing(2);
    }

    /**
     * Adds a draggable version of the widget to the panel
     *
     * @param widget Widget to add
     */
    public void add(DraggableWrapperWidget widget) {
        dragController.makeDraggable(widget);
        super.add(widget);
    }

    /**
     * Override remove to make a copy of the widget
     *
     * @param widget Widget to remove
     * @return boolean whether remove was successfull
     */
    @Override
    public boolean remove(Widget widget) {
        int index = getWidgetIndex(widget);
        if (index != -1 && widget instanceof DraggableWrapperWidget) {
            DraggableWrapperWidget clone = ((DraggableWrapperWidget) widget).cloneWidget();
            dragController.makeDraggable(clone);
            insert(clone, index);
        }
        return super.remove(widget);
    }


}
